package com.rtsapp.server.network.protocol.crypto;

import java.util.Random;

/**
 * RSAKeyUtils
 * 所有的代码都必须是线程安全的
 */
public class KeyUtils {

    private static final ThreadLocal<Random> randomHold = new ThreadLocal<>();

    /**
     * 产生64位RC4加密key
     * @return
     */
    public static byte[] generateRC4CrpytKey() {
        Random r  = randomHold.get();
        if( r == null ){
            r = new Random();
            randomHold.set( r );
        }

        byte[] bytes = new byte[64];
        for( int i = 0; i < bytes.length ;i++ ){
            bytes[i] = (byte)( 1 + r.nextInt( 127 ) );
        }
        return bytes;
    }


    /**
     * 克隆字节
     * @param bytes
     * @return
     */
    public static byte[] cloneBytes(byte[] bytes) {
        byte[] result = new byte[bytes.length];
        System.arraycopy(bytes, 0, result, 0, bytes.length);
        return result;
    }


    /**
     * 字节是否一致
     * @param b1
     * @param b2
     * @return
     */
    public static boolean bytesEquals(byte[] b1, byte[] b2) {
        if (b1.length != b2.length) {
            return false;
        }

        for (int i = 0; i < b1.length; i++) {
            if (b1[i] != b2[i]) {
                return false;
            }
        }

        return true;
    }

}
